<?php


namespace app\index\model;


use think\Model;

class Customer extends Model
{
    public $fixed_tags=['FaceBook','Instagram'];

    public static function getList(){
        $CustomerClass = new self();

        $where['del_flag']=['=',0];
        $data=$CustomerClass->where($where)->field('id,nick_name name,create_group')->select()->toArray();

        foreach ($data as $key=>$value){
            if($value['create_group']) {
                $customer_list[$value['create_group']][] = ['id'=>$value['id'],'name'=>$value['name']];
            }else{
                $customer_list[0][]=$value;
            }
        }
        return $customer_list;
    }

    public static function getCustomerList($search_param,$page_param): array
    {
        $CustomerClass = new self();

        ['action_role'=>$action_role,'search_user'=>$search_user,'group'=>$group]=ActionRole::checkUserActionRole('customer');

        if(!empty($group)){
            $where['c.create_group']=['=',$group];
        }else if(is_numeric($search_param['group_id']) && $search_param['group_id']){
            $where['c.create_group']=['=',$search_param['group_id']];
        }

        if(!empty($search_user)) {
            $where['c.create_user'] = ['in', $search_user];
        }else if(is_numeric($search_param['user_id'])){
            $search_user=[$search_param['user_id']];
            $where['c.create_user'] = ['in', $search_user];
        }

        if(is_numeric($search_param['type'])){
            if($search_param['type']===0) {
                $where['c.type'] = ['=',0];
            }else{
                $where['c.type'] = ['in',[1,2]];
            }
        }
        $where['c.del_flag']=['=',0];
        if (!empty($search_param['tags'])) {
            $customer_tags_ids=$CustomerClass->name('customer_tags')->where('del_flag',0)->whereIn('tags_id',$search_param['tags'])->field('group_concat(customer_id) id')->find();
            if(empty($customer_tags_ids) || $customer_tags_ids['id']===null) {
                return ['status'=>true,'result'=>['data'=>[],'total'=>0,'action_role'=>$action_role]];
            }
            $where['c.id'] = ['in', explode(',',$customer_tags_ids['id'])];
        }
        if (!empty($search_param['create_time'])) {
            $where['c.create_time']=['between',[$search_param['create_time'].' 00:00:00',$search_param['create_time'].' 23:59:59']];
        }
        if (!empty($search_param['customer_id'])) {
            $where['c.id']=['=',$search_param['customer_id']];
        }
        if (!empty($search_param['search_key']) && !empty($search_param['search_value'])) {
            if($search_param['search_key']==='nick_name'){
                $where['c.'.$search_param['search_key']]=['like','%'.$search_param['search_value'].'%'];
            }else if($search_param['search_key']==='id'){
                $ids=explode(' ',$search_param['search_value']);
                $where['c.'.$search_param['search_key']]=['in',$ids];
            }else {
                $where['c.' . $search_param['search_key']] = ['=', $search_param['search_value']];
            }
        }

        $OrderClass=new Order();
        $order_sql = $OrderClass->where('customer_id =c.id')->where('del_flag',0)->where('order_status',1)->where('pay_type','in',[2,3])->field('round(sum(total_price - amount_paid-amount_discount-tip_paid),2) unpaid_price')->buildSql();
        $paid_order_sql = $OrderClass->where('customer_id =c.id')->where('del_flag',0)->where('order_status',1)->where('pay_type','in',[3,4])->field('round(sum(amount_paid-tip_paid),2) paid_price')->buildSql();


        $obj=$CustomerClass->name('customer c')->where($where)
            ->join('__CUSTOMER_TAGS__ ct','c.id=ct.customer_id and ct.del_flag=0','left')
            ->join('__TAGS__ t','ct.tags_id=t.id and t.del_flag=0','left')
            ->join('__COUNTRY__ cty','c.country=cty.id','left')
            ->field('c.id,c.nick_name,c.email,cty.country_name,c.city,c.phone,c.remark,c.address,group_concat(DISTINCT t.tag_text ORDER BY t.id) tags,c.home_page,c.type,IFNULL('.$order_sql.',0) unpaid_price,IFNULL('.$paid_order_sql.',0) paid_price')
            ->group('c.id')
            ->order('c.'.$search_param['order_by'].' '.$search_param['sort_by'])
            ->paginate($page_param['page_size'],false,['page'=>$page_param['page_num']]);

        if($obj->isEmpty()){
            return ['status'=>true,'result'=>['data'=>[],'total'=>0,'action_role'=>$action_role]];
        }
        $count=$obj->total();
        $data=$obj->items();


        return ['status'=>true,'result'=>['data'=>$data,'total'=>$count,'action_role'=>$action_role]];
    }

    public static function getCustomerByName($name,$group): array
    {
        if(!$group){
            return ['status'=>false,'result'=>'未选择组'];
        }

        $CustomerClass = new self();
        ['search_user'=>$search_user]=ActionRole::checkUserActionRole('customer_search');

        if(!empty($search_user)) {
            $where['create_user'] = ['in', $search_user];
        }


        $where['create_group']=['=',$group];
        $where['nick_name']=['=',$name];
        $where['del_flag']=['=',0];
        $data=$CustomerClass->where($where)->field('id,email,phone,nick_name,customer_name')->find();

        if(empty($data)){
            return ['status'=>false,'result'=>'未找到用户'];
        }
        return ['status'=>true,'result'=>['data'=>$data]];
    }

    public static function getCustomerListByName($name,$group): array
    {
        $CustomerClass = new self();

        ['search_user'=>$search_user]=ActionRole::checkUserActionRole('customer_search');

        $where['create_group']=['=',$group];
        if(!empty($search_user)) {
            $where['create_user'] = ['in', $search_user];
        }

//        $where['nick_name']=['like','%'.$name.'%'];
        $map['nick_name|ins_name|other_name|customer_name'] = ['like','%' . $name . '%'];
        $where['del_flag']=['=',0];
        $data=$CustomerClass->where($where)->where($map)->field('id value,nick_name label,ins_name,other_name')->select()->toArray();

        if(empty($data)){
            return ['status'=>true,'result'=>['data'=>[]]];
        }
        return ['status'=>true,'result'=>['data'=>$data]];
    }

    public static function getCustomerById($id): array
    {
        $CustomerClass = new self();
        ['search_user'=>$search_user,'group'=>$group]=ActionRole::checkUserActionRole('customer');
        if(!empty($search_user)) {
            $where['create_user']=['in',$search_user];
        }
        if(!empty($group)){
            $where['create_group']=['=',$group];
        }
        $where['id']=['=',$id];
        $where['del_flag']=['=',0];
        $data=$CustomerClass->where($where)->field('id,email,phone,nick_name,ins_name,other_name,customer_name,zip_code,country,city,address,home_page,create_group `group`,birthday,remark,ship_fee')->find();

        if(empty($data)){
            return ['status'=>false,'result'=>'未找到客户'];
        }

        $tags_data=$CustomerClass->name('customer_tags ct')->join('tags t','ct.tags_id=t.id','left')->where('ct.del_flag',0)->where('t.del_flag',0)->where('ct.customer_id',$id)->field('t.tag_text')->select()->toArray();
        $tags=[];
        if(!empty($tags_data)) {
            foreach ($tags_data as $value) {
                $tags[] = $value['tag_text'];
            }
        }
        return ['status'=>true,'result'=>['data'=>$data,'tags'=>$tags]];
    }

    public static function createCustomer($data,$tags): array
    {
        $CustomerClass = new self();
        $TagClass=new Tags();
        $insert_tag_data=[];
        $insert_customer_tags=[];
        $tags_id=[];

        if(!empty($tags)){
            $tags_data=$TagClass->whereIn('tag_text',$tags)->where('del_flag',0)->field('id,tag_text')->select()->toArray();
            $tag_list=[];
            foreach ($tags_data as $value){
                $tag_list[$value['tag_text']]=$value['id'];
            }

            foreach ($tags as $value){
                if(!isset($tag_list[$value])){
                    $insert_tag_data[]=['tag_text'=>$value];
                }else{
                    $tags_id[]=$tag_list[$value];
                }
            }
        }

        $CustomerClass->startTrans();
        try {
            $CustomerClass->data($data);
            $result=$CustomerClass->save();
            if($result===false){
                return ['status'=>false,'result'=>'保存失败'];
            }
            $customer_id=$CustomerClass->id;

            if(!empty($insert_tag_data)) {
                $result=$TagClass->saveAll($insert_tag_data);
                if($result===false){
                    return ['status'=>false,'result'=>'保存标签失败'];
                }
                foreach ($result as $value){
                    $insert_customer_tags[]=['customer_id'=>$customer_id,'tags_id'=>$value['id']];
                }
            }
            if(!empty($tags_id)){
                foreach ($tags_id as $value){
                    $insert_customer_tags[]=['customer_id'=>$customer_id,'tags_id'=>$value];
                }
            }
            if(!empty($insert_customer_tags)){
                $result=$CustomerClass->name('customer_tags')->insertAll($insert_customer_tags);
                if($result===false){
                    return ['status'=>false,'result'=>'保存标签失败2'];
                }
            }

            $CustomerClass->commit();
            return ['status'=>true,'result'=>'添加成功'];
        }catch (\Exception $e) {
            $CustomerClass->rollback();
            trace($e->getMessage(),'error');
            return ['status'=>false,'result'=>'添加失败'.$e->getMessage()];
        }
    }

    public static function updateCustomer($id,$data,$tags): array
    {
        $CustomerClass = new self();
        $TagClass=new Tags();
        $insert_tag_data=[];
        $insert_customer_tags=[];
        $tags_id=[];

        $customer_data=$CustomerClass->where('del_flag',0)->where('id','=',$id)->field('id,create_group')->find();
        if(empty($customer_data)){
            return ['status'=>false,'result'=>'未找到客户'];
        }

        $check=$CustomerClass->where('nick_name','=',$data['nick_name'])->where('create_group',$customer_data['create_group'])->where('del_flag',0)->where('id','<>',$id)->field('id,email,phone,nick_name,customer_name')->find();
        if(!empty($check)){
            return ['status'=>false,'result'=>'客户名称已被使用'];
        }
        if(!empty($tags)){
            $tags_data=$TagClass->whereIn('tag_text',$tags)->where('del_flag',0)->field('id,tag_text')->select()->toArray();
            $tag_list=[];
            foreach ($tags_data as $value){
                $tag_list[$value['tag_text']]=$value['id'];
            }

            foreach ($tags as $value){
                if(!isset($tag_list[$value])){
                    $insert_tag_data[]=['tag_text'=>$value];
                }else{
                    $insert_customer_tags[$tag_list[$value]]=['customer_id'=>$id,'tags_id'=>$tag_list[$value]];
                }
            }
        }

        $CustomerClass->startTrans();
        try {
            $result=$CustomerClass->save($data,['id'=>$id]);
            if($result===false){
                return ['status'=>false,'result'=>'保存失败'];
            }

            if(!empty($insert_tag_data)) {
                $result=$TagClass->saveAll($insert_tag_data);
                if($result===false){
                    return ['status'=>false,'result'=>'保存标签失败'];
                }
                foreach ($result as $value){
                    $insert_customer_tags[$value['id']]=['customer_id'=>$id,'tags_id'=>$value['id']];
                }
            }
            $old_customer_tags=$CustomerClass->name('customer_tags')->where('customer_id',$id)->where('del_flag',0)->select()->toArray();
            foreach ($old_customer_tags as $value){
                if(isset($insert_customer_tags[$value['tags_id']])){
                    unset($insert_customer_tags[$value['tags_id']]);
                }else{
                    $tags_id[]=$value['id'];
                }
            }
            if(!empty($tags_id)){
                $result=$CustomerClass->name('customer_tags')->whereIn('id',$tags_id)->update(['del_flag'=>1]);
                if($result===false){
                    return ['status'=>false,'result'=>'删除标签失败'];
                }
            }
            if(!empty($insert_customer_tags)){
                $result=$CustomerClass->name('customer_tags')->insertAll($insert_customer_tags);
                if($result===false){
                    return ['status'=>false,'result'=>'保存标签失败2'];
                }
            }

            $CustomerClass->commit();
            return ['status'=>true,'result'=>'更新成功'];
        }catch (\Exception $e) {
            $CustomerClass->rollback();
            trace($e->getMessage(),'error');
            return ['status'=>false,'result'=>'更新失败'.$e->getMessage()];
        }
    }

    /**
     * checkCustomer
     * 检查重复客户 获取客户ID
     * @url
     * @method
     * @param string $customer_name 客户名
     * @param int $group 组
     * @return array|bool|float|int|mixed|object|\stdClass|null
     * @author Asira
     * @date 2021/2/19
     */
    public static function checkCustomer($customer_name,$group){
        $customer_name=trim($customer_name);
        $CustomerClass = new Customer();
        ['status'=>$status,'result'=>$result]=$CustomerClass::getCustomerByName($customer_name,$group);
        if($status===false) {
            $CustomerClass->data(['nick_name' => $customer_name, 'customer_name' => $customer_name, 'country' => 2,'create_user'=>session('Login_user')['id'],'create_group'=>$group]);
            $CustomerClass->save();
            $customer_id = $CustomerClass->id;
        }else{
            $customer_id=$result['data']['id'];
        }
        return $customer_id;
    }

    public static function getEmailByName($name,$id)
    {
        $CustomerClass = new self();
        $name=trim($name);

        $obj=$CustomerClass->where('nick_name',$name)
            ->where('email','not null')
            ->where('email','<>','')
            ->where('del_flag',0);
        if(!empty($id)) {
            $obj->where('id', '<>', $id);
        }
        $row=$obj->field('id,email,country,city,address,zip_code,phone')->find();
        if (empty($row)){
            return ['status'=>false,'result'=>'用户名不存在'];
        }
        $CustomerTags=new CustomerTags();
        $tags=$CustomerTags->alias('ct')->join('tags t','ct.tags_id=t.id','left')->where('ct.customer_id','=',$row['id'])->where('ct.del_flag','=',0)->where('t.del_flag','=',0)->column('t.tag_text');
        return ['status'=>true,'result'=>['data'=>$row,'tags'=>$tags]];
    }

    /**
     * 获取单人的销售额清单
     * create by yhb on 2021/4/6 18:16
     * @param $search_param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException]
     */
    public function getSalesDetail($search_param)
    {
        $where['c.del_flag']=['=',0];
        $where['co.del_flag']=['=',0];
//        $where['co.gift']=['<>',1];
        $where['co.create_user']=['<>',0];
        ['action_role'=>$action_role,'search_user'=>$search_user,'group'=>$group]=ActionRole::checkUserActionRole('report_sales');
        if(!empty($group)){
            $where['co.create_group']=['=',$group];
        }else if (is_numeric($search_param['group_id']) && $search_param['group_id']) {
            $where['co.create_group'] = ['=', $search_param['group_id']];
        }

        if(!empty($search_user)) {
            $where['co.create_user'] = ['in', $search_user];
        }else if(is_array($search_param['user']) && !empty($search_param['user'])){
            $search_user=$search_param['user'];
            $where['co.create_user'] = ['in', $search_user];
        }

        if (!empty($search_param['create_time'])) {
            $where['co.create_time']=['between',[$search_param['create_time'][0].' 00:00:00',$search_param['create_time'][1].' 23:59:59']];
        }

        $obj=$this->alias('c')
            ->join('customer_order co','c.id=co.customer_name','left')
            ->where($where)
            ->where('co.create_user',$search_param['id'])
            ->field('c.customer_name,co.cn_name,co.en_name,co.create_time,co.amount,co.selling_price')
            ->select();
        if(!empty($obj)){
            $sales_detail = $obj->toArray();
        }else{
            return [];
        }
        return ['status'=>true,'result'=>['sales_detail'=>$sales_detail,'action_role'=>$action_role]];
    }

    public static function mergeCustomer($ids)
    {
        $customerClass=new self();
        $orderClass=new Order();
        $customerOrderClass=new CustomerOrder();
        $customer_data=$customerClass->where('id','in',$ids)->select();
        $notNull=0;
        $ids=[];
        $id='';
        $group=0;
        foreach ($customer_data as $k=>$v){
            if($k===0) {
                $group = $v['create_group'];
            }elseif($group!==$v['create_group']){
                return ['status'=>1,'result'=>'不能合并不同组的客户'];
            }
            if ($v['email']){
                $notNull++;
                $id=$v['id'];
            }else{
                $ids[]=$v['id'];
            }
        }
        if ($notNull===1){
            $customerClass->startTrans();
            try {
                $result=$orderClass->whereIn('customer_id',$ids)->update(['customer_id'=>$id]);
                if ($result===false){
                    return ['status'=>1,'result'=>'合并失败'];
                }
                $result=$customerOrderClass->whereIn('customer_name',$ids)->update(['customer_name'=>$id]);
                if ($result===false){
                    return ['status'=>1,'result'=>'合并失败'];
                }
                $result=$customerClass->where('id','in',$ids)->update(['del_flag'=>1]);
                if ($result===false){
                    return ['status'=>1,'result'=>'合并失败'];
                }
                $customerClass->commit();
                return ['status'=>0,'result'=>'合并成功'];
            }catch (\Exception $e) {
                $customerClass->rollback();
                trace($e->getMessage(),'error');
                return ['status'=>1,'result'=>'更新失败'.$e->getMessage()];
            }
        }else{
            return ['status'=>2,'result'=>$customer_data];
        }
    }

    public static function chooseMerge($ids,$id)
    {
        $customerClass=new self();
        $orderClass=new Order();
        $customerOrderClass=new CustomerOrder();
        $customerClass->startTrans();
        try {
            $result=$orderClass->whereIn('customer_id',$ids)->update(['customer_id'=>$id]);
            if ($result===false){
                return ['status'=>false,'result'=>'合并失败'];
            }
            $result=$customerOrderClass->whereIn('customer_name',$ids)->update(['customer_name'=>$id]);
            if ($result===false){
                return ['status'=>false,'result'=>'合并失败'];
            }
            $result=$customerClass->where('id','in',$ids)->update(['del_flag'=>1]);
            if ($result===false){
                return ['status'=>false,'result'=>'合并失败'];
            }
            $customerClass->commit();
            return ['status'=>true,'result'=>'合并成功'];
        }catch (\Exception $e) {
            $customerClass->rollback();
            trace($e->getMessage(),'error');
            return ['status'=>false,'result'=>'更新失败'.$e->getMessage()];
        }
    }
}